<template>
  <div class="login-container">
    <div class="top-bg">
      <div class="welcome-text">
        <p>您好，</p>
        <p>欢迎体验ai问答</p>
      </div>
    </div>

    <div class="login-form">
      <div class="login-tabs">
        <div class="tab active">账号登录</div>
      </div>

      <form>
        <div class="form-group">
          <label class="label">账号</label>
          <input
            type="text"
            v-model="username"
            placeholder="请输入账号"
            class="input-field"
            :class="{ 'error-border': errors.username }"
          >
          <p v-if="errors.username" class="error-message">{{ errors.username }}</p>
        </div>

        <div class="form-group">
          <label class="label">密码</label>
          <input
            type="password"
            v-model="password"
            placeholder="请输入密码"
            class="input-field"
            :class="{ 'error-border': errors.password }"
          >
          <p v-if="errors.password" class="error-message">{{ errors.password }}</p>
        </div>

        <button type="button" class="login-btn" @click="login">登录</button>
        <button type="button" class="register-btn" @click="goToRegister">注册</button>
        <button type="button" class="guest-btn" @click="guestLogin">游客登录</button>
      </form>
    </div>
  </div>
</template>

<script>
import { API_BASE_URL } from '@/utils/api-base.js'
import { API_ADMIN } from '../../utils/api-base';

export default {
  data() {
    return {
      username: '',
      password: '',
      errors: {
        username: '',
        password: ''
      }
    }
  },
  methods: {
    goToRegister() {
      uni.navigateTo({
        url: '/pages/register/register'
      });
    },
    validateForm() {
      let isValid = true;
      this.errors = {
        username: '',
        password: ''
      };

      // 账号验证
      if (!this.username.trim()) {
        this.errors.username = '请输入账号';
        isValid = false;
      }

      // 密码验证
      if (!this.password) {
        this.errors.password = '请输入密码';
        isValid = false;
      } else if (this.password.length < 6 || this.password.length > 20) {
        this.errors.password = '密码长度必须在6-20位之间';
        isValid = false;
      }

      return isValid;
    },
    async login() {
      // 表单验证
      if (!this.validateForm()) {
        return;
      }

      // 显示加载状态
      uni.showLoading({ title: '登录中...' });

      try {
        // 调用登录接口
        const res = await uni.request({
          url: API_BASE_URL + '/api/auth/login',
          method: 'POST',
          data: {
            userName: this.username.trim(),
            password: this.password
          },
          header: {
            'Content-Type': 'application/json'
          }
        });

        uni.hideLoading();
        console.log('登录响应:', res);
        
        // 处理HTTP错误状态码
        if (res.statusCode < 200 || res.statusCode >= 300) {
          let errorMsg = `登录失败 (${res.statusCode})`;
          
          // 解析后端返回的错误信息
          if (res.data && res.data.message) {
            errorMsg = res.data.message;
          } else if (res.statusCode === 400 && res.data.errors) {
            // 处理模型验证错误
            const firstError = Object.values(res.data.errors)[0][0];
            errorMsg = firstError || errorMsg;
          }
          
          // 显示错误提示
          uni.showToast({
            title: errorMsg,
            icon: 'none'
          });
          return;
        }

        // 处理业务逻辑结果
        const result = res.data;
        
        // 验证返回结果的基本结构
        if (!result || typeof result !== 'object') {
          uni.showToast({
            title: '登录失败，返回数据格式错误',
            icon: 'none'
          });
          return;
        }
        
        if (result.success) {
          // 验证token是否存在
          if (!result.token) {
            uni.showToast({
              title: '登录失败，未获取到token',
              icon: 'none'
            });
            return;
          }
          
          // 保存token
          uni.setStorageSync('token', result.token);
          
          // 获取用户ID（兼容可能的不同字段名）
          const userId = result.userInfo.id || result.userId || (result.user && (result.user.id || result.user.userId));
          console.log('用户ID:', userId);
          
          if (userId) {
            // 登录成功后，调用用户信息接口获取最新数据
            this.fetchUserInfo(userId);
          } else {
            // 处理没有用户ID的情况，使用返回的用户信息
            const userData = result.user || {};
            this.handleUserInfo(userData);
          }
        } else {
          // 登录失败处理
          const errorMsg = result?.message || '登录失败，请检查账号密码';
          if (errorMsg.includes('用户名') || errorMsg.includes('userName')) {
            this.errors.username = errorMsg;
          } else if (errorMsg.includes('密码') || errorMsg.includes('password')) {
            this.errors.password = errorMsg;
          } else if (errorMsg.includes('状态') || errorMsg.includes('status')) {
            uni.showToast({
              title: errorMsg,
              icon: 'none'
            });
          } else {
            uni.showToast({
              title: errorMsg,
              icon: 'none'
            });
          }
        }
      } catch (err) {
        uni.hideLoading();
        console.error('登录请求失败', err);
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      }
    },
    // 新增：获取用户信息接口，与注册保持一致
    fetchUserInfo(userId) {
      const token = uni.getStorageSync('token');
      if (!token) return;
      
      uni.request({
        url: `${API_BASE_URL}/api/user/${userId}`,
        method: 'GET',
        header: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data) {
            // 用接口返回的最新数据更新本地存储
            // console.log(token);
            
            this.handleUserInfo(res.data);
          } else {
            console.error('获取用户信息失败', res);
            // 使用登录接口返回的用户信息作为备选
            const userData = res.data?.user || {};
            this.handleUserInfo(userData);
          }
        },
        fail: (err) => {
          console.error('登录后获取用户信息失败', err);
          // 获取用户信息失败时的降级处理
          uni.showToast({
            title: '获取用户信息失败',
            icon: 'none'
          });
        }
      });
    },
    // 处理用户信息并跳转
    handleUserInfo(userData) {
      console.log('处理用户信息:', userData);
      
      // 构建完整的用户信息，确保与注册流程保持一致
      const userInfo = {
        id: userData.id || userData.userId || '',
        userName: userData.userName || '用户',
        email: userData.email || '',
        phoneNumber: userData.phoneNumber || '',
        avatarUrl: userData.avatarUrl || '',
        status: userData.status || 'active',
        roleTypes: userData.roles[0] === '管理员' ? 'admin' : 'user',  // 使用后端返回的roleTypes
        roles: userData.roles || ['普通用户']  
        // roleTypes: userData.roles || 'user',  // 角色类型
        // roleName: userData.roleName || (userData.roles[0] === 'admin' ? '管理员' : '普通用户'),
        // permissions: userData.permissions || [],
      };      

      // 保存用户信息到本地存储
      uni.setStorageSync('userInfo', userInfo);
      console.log('保存用户信息到本地存储:', userInfo);
      
      
      // 登录成功提示
      uni.showToast({
        title: '登录成功',
        icon: 'success'
      });      
      // 判断是否为管理员
      if (userInfo.roles.includes('管理员') || userInfo.roleTypes.includes('admin')) {
        // 将必要信息编码后传递给PC端
        const encodedData = encodeURIComponent(JSON.stringify({
          token: uni.getStorageSync('token'),
          userInfo: userInfo
        }));
        // 一样跳转至聊天界面
        // uni.reLaunch({ url: '/pages/chat/chat' });

        // 跳转到PC端管理后台（带参数）
        window.location.href = `${API_ADMIN}/admin-redirect?data=${encodedData}`;
      } else {
        // 普通用户跳转到聊天页面
        uni.reLaunch({ url: '/pages/chat/chat' });
      }
    },
    // 游客登录逻辑
    guestLogin() {
      uni.showLoading({ title: '游客登录中...' });
      
      // 生成符合系统规范的游客ID
      const timestamp = Date.now().toString(16);
      const randomStr = Math.floor(Math.random() * 1000000000).toString(16);
      const guestId = `guest-${timestamp}-${randomStr}`;
      
      // 构建符合角色规范的游客信息
      const guestUserInfo = {
        id: guestId,
        userName: '游客',
        roleType: 'guest',
        roleName: '游客',
        roleIds: [],
        status: 'active',
        permissions: [],
        email: '',
        phoneNumber: '',
        // avatarUrl: ''
        avatarUrl: 'https://picsum.photos/200/200?random=guest'
      };
      
      // 存储临时token和游客信息
      uni.setStorageSync('token', `guest-token-${guestId}`);
      uni.setStorageSync('userInfo', guestUserInfo);
      
      // 隐藏加载状态并提示
      uni.hideLoading();
      uni.showToast({
        title: '已以游客身份进入',
        icon: 'success'
      });
      
      // 跳转到聊天页面
      setTimeout(() => {
        uni.reLaunch({
          url: '/pages/chat/chat'
        });
      }, 600);
    }
  },
  mounted() {
    // 检查是否已有登录状态
    const token = uni.getStorageSync('token');
    const userInfo = uni.getStorageSync('userInfo');
    
    // 已登录用户自动跳转
    if (token && userInfo) {
      // 统一跳转到聊天页面
      uni.reLaunch({
        url: '/pages/chat/chat'
      });
    }
  }
}
</script>

<style scoped>
/* 样式部分保持不变 */
div, p, form, label, input, button, html, body, #app {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html, body, #app {
  height: 100%;
  width: 100%;
}

.login-container {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.top-bg {
  background: linear-gradient(135deg, #e0f0ff 0%, #b3d9ff 100%);
  padding: 20px 24px 50px;
  color: #333;
  position: relative;
  z-index: 1;
  flex: 0 0 calc(35% - 30px);
  display: flex;
  flex-direction: column;
}

.welcome-text {
  margin-top: auto;
}

.welcome-text p:first-child {
  font-size: 28px;
  margin-bottom: 12px;
}

.welcome-text p:last-child {
  font-size: 18px;
  opacity: 0.9;
}

.top-bg::after {
  content: '';
  position: absolute;
  right: -30px;
  top: 35%;
  width: 200px;
  height: 200px;
  background-color: rgba(255, 255, 255, 0.5);
  border-radius: 50%;
}

.login-form {
  background-color: white;
  border-top-left-radius: 30px;
  border-top-right-radius: 30px;
  padding: 30px 24px 50px;
  margin-top: -30px;
  box-shadow: 0 -4px 15px rgba(0, 0, 0, 0.05);
  flex: 1;
  position: relative;
  z-index: 2;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

.login-tabs {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
}

.tab {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  padding-bottom: 8px;
  position: relative;
}

.tab.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 3px;
  background-color: #66b3ff;
  border-radius: 3px;
}

.form-group {
  margin-bottom: 25px;
  position: relative;
}

.label {
  display: block;
  font-size: 14px;
  color: #333;
  margin-bottom: 10px;
  font-weight: 500;
}

.input-field {
  width: 100%;
  padding: 16px 12px;
  margin-bottom: 10px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 16px;
  background: transparent;
  transition: all 0.3s;
  min-height: 50px;
}

.input-field.error-border {
  border-color: #ff4d4f;
}

.input-field:focus {
  outline: none;
  border-color: #66b3ff;
}

.error-message {
  color: #ff4d4f;
  font-size: 13px;
  height: 18px;
  line-height: 18px;
  text-align: left;
}

/* 按钮样式 */
.login-btn, .register-btn, .guest-btn {
  width: 100%;
  padding: 16px 10px;
  border-radius: 8px;
  font-size: 17px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  border: none;
  margin-bottom: 15px;
}

.login-btn {
  background-color: #1890ff;
  color: white;
}

.login-btn:hover {
  background-color: #096dd9;
}

.register-btn {
  background-color: white;
  color: #1890ff;
  border: 1px solid #1890ff;
}

.register-btn:hover {
  background-color: #f0f7ff;
}

.guest-btn {
  background-color: #f5f5f5;
  color: #666;
}

.guest-btn:hover {
  background-color: #e8e8e8;
}
</style>